package com.framework.util;



import com.framework.res.LineStringToList;
import com.softcomputo.commons.exception.GeneralRuntimeException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.List;

public class ConvertidorRipAObjeto {
	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.FIELD)
	public @interface Convertir {
		int pos();
	}
	
	
	/* metodo que reporta el objeto */
	public static <T> T convertirAObjeto(List<String> rips, Class<T> tipo){
		try { 
			T t = tipo.newInstance();
			Field[] fields = tipo.getDeclaredFields();
			fields = reOrdenarField(fields);
			int count = 0;
			for (Field field : fields) {
				if(field.getAnnotation(Convertir.class) != null){
					field.setAccessible(true);
					String value = rips.get(count);
					field.set(t, getValueParaTipo(value, field.getType())); 
					count++;
				}
			}
			return t;
		} catch  (Exception e) {
			e.printStackTrace();
			throw new GeneralRuntimeException(e.getMessage(), e);
		}
	}
	
	
	private static Object getValueParaTipo(String value, Class<?> type) {
		if(type == Integer.class){
			if(!value.trim().isEmpty() && value.matches("[0-9]*$")){
				return Integer.parseInt(value);
			}else{
				return 0;
			}
		}else if(type == Double.class || type == double.class){
			if(!value.trim().isEmpty() && value.matches("[0-9,.]*$")){
				return Double.parseDouble(value);
			}else{
				return 0D;
			}
		}else if(type == Timestamp.class){
			if(!(value+"").trim().isEmpty()){
				return LineStringToList.convertTo("" + value);	
			}else{
				return null;
			}
		}
		return value;
	}


	/**
	 * Metodo para ordenar 
	 * */
	
	private static Field[] reOrdenarField(Field[] fields) {
		for (int i = 0; i < fields.length; i++) {
				for (int j = 0; j < fields.length; j++) {
					Convertir gtorViewPosition_i = fields[i].getAnnotation(Convertir.class);
					Convertir gtorViewPosition_j = fields[j].getAnnotation(Convertir.class);
					if(gtorViewPosition_j != null && gtorViewPosition_i != null){
						if(gtorViewPosition_i.pos() < gtorViewPosition_j.pos()){
							Field field_temp = fields[i];
							fields[i] = fields[j];
							fields[j] = field_temp;
						}
					}
				}
		}
		return fields;
	 }
	
}
